<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库智能查询助手</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .chat-container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .chat-history {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            background-color: #fafafa;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 5px;
            max-width: 80%;
            clear: both;
            word-wrap: break-word;
        }
        .user-message {
            background-color: #007bff;
            color: white;
            float: right;
        }
        .ai-message {
            background-color: #e9ecef;
            color: black;
            float: left;
        }
        .sql-message {
            background-color: #d1ecf1;
            color: #0c5460;
            float: left;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
        }
        .result-message {
            background-color: #d4edda;
            color: #155724;
            float: left;
        }
        .analysis-message {
            background-color: #fff3cd;
            color: #856404;
            float: left;
        }
        /* 清除浮动影响 */
        .chat-history::after {
            content: "";
            display: table;
            clear: both;
        }
        .input-area {
            display: flex;
            gap: 10px;
        }
        #user-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        #send-btn {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        #send-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .typing-indicator {
            color: #6c757d;
            font-style: italic;
        }
        .section-title {
            font-weight: bold;
            margin-top: 10px;
            margin-bottom: 5px;
            color: #495057;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>数据库智能查询助手</h1>
        <div id="chat-history" class="chat-history"></div>
        <div class="input-area">
            <input type="text" id="user-input" placeholder="请输入数据库查询问题，例如：查询2025年的所有事件..." />
            <button id="send-btn">发送</button>
        </div>
    </div>

    <script>
        const chatHistory = document.getElementById('chat-history');
        const userInput = document.getElementById('user-input');
        const sendBtn = document.getElementById('send-btn');
        let currentAiMessage = null;

        function addMessage(message, messageType) {
            const messageDiv = document.createElement('div');
            let className = 'message ';
            
            switch(messageType) {
                case 'user':
                    className += 'user-message';
                    break;
                case 'ai':
                    className += 'ai-message';
                    break;
                case 'sql':
                    className += 'sql-message';
                    break;
                case 'result':
                    className += 'result-message';
                    break;
                case 'analysis':
                    className += 'analysis-message';
                    break;
                default:
                    className += 'ai-message';
            }
            
            messageDiv.className = className;
            
            // 如果是SQL消息，添加标题和格式化
            if (messageType === 'sql') {
                messageDiv.innerHTML = '<div class="section-title">生成的SQL:</div>' + message;
            } 
            // 如果是结果消息，添加标题
            else if (messageType === 'result') {
                messageDiv.innerHTML = '<div class="section-title">查询结果:</div>' + message;
            }
            // 如果是分析消息，添加标题
            else if (messageType === 'analysis') {
                messageDiv.innerHTML = '<div class="section-title">分析过程:</div>' + message;
            }
            // 默认情况
            else {
                messageDiv.textContent = message;
            }
            
            chatHistory.appendChild(messageDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight;
            return messageDiv;
        }

        function showTyping() {
            const typingDiv = document.createElement('div');
            typingDiv.className = 'message ai-message typing-indicator';
            typingDiv.id = 'typing-indicator';
            typingDiv.textContent = '正在分析查询并生成SQL...';
            chatHistory.appendChild(typingDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }

        function hideTyping() {
            const typingIndicator = document.getElementById('typing-indicator');
            if (typingIndicator) {
                typingIndicator.remove();
            }
        }

function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;

    // 添加用户消息
    addMessage(message, 'user');
    userInput.value = '';
    sendBtn.disabled = true;

    // 显示正在输入指示器
    showTyping();

    try {
        // 使用 Fetch API 发送 POST 请求到数据库API，并处理流式响应
        const response = fetch('/api/v1/database', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                question: message,
                session_id: 'default'
            })
        });

        response.then(resp => {
            const reader = resp.body.getReader();
            const decoder = new TextDecoder();

            hideTyping();
            
            // 创建消息元素用于显示流式内容
            let analysisMessageElement = null;
            let sqlMessageElement = null;
            let resultMessageElement = null;
            let analysisContent = '';
            let sqlContent = '';
            
            function readStream() {
                reader.read().then(({ done, value }) => {
                    if (done) {
                        sendBtn.disabled = false;
                        userInput.focus();
                        return;
                    }

                    const text = decoder.decode(value);
                    const lines = text.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6); // 移除 'data: ' 前缀
                            if (data === '[DONE]') {
                                sendBtn.disabled = false;
                                userInput.focus();
                                return;
                            }

                            try {
                                const jsonData = JSON.parse(data);
                                
                                if (jsonData.error) {
                                    if (!analysisMessageElement) {
                                        analysisMessageElement = addMessage(`错误: ${jsonData.error}`, 'analysis');
                                    } else {
                                        analysisMessageElement.textContent += `\n错误: ${jsonData.error}`;
                                    }
                                    sendBtn.disabled = false;
                                    userInput.focus();
                                    return;
                                } else if (jsonData.content) {
                                    // 处理流式分析内容
                                    if (!analysisMessageElement) {
                                        analysisMessageElement = addMessage('', 'analysis');
                                    }
                                    analysisContent += jsonData.content;
                                    analysisMessageElement.textContent = `分析过程:\n${analysisContent}`;
                                    chatHistory.scrollTop = chatHistory.scrollHeight;
                                } else if (jsonData.sql_query && jsonData.result) {
                                    // 显示最终的SQL和结果
                                    sqlMessageElement = addMessage(jsonData.sql_query, 'sql');
                                    resultMessageElement = addMessage(jsonData.result, 'result');
                                }
                            } catch (e) {
                                console.error('解析JSON失败:', e);
                            }
                        }
                    }

                    readStream(); // 继续读取流
                }).catch(error => {
                    hideTyping();
                    if (!analysisMessageElement) {
                        analysisMessageElement = addMessage(`网络错误: ${error.message}`, 'analysis');
                    } else {
                        analysisMessageElement.textContent += `\n网络错误: ${error.message}`;
                    }
                    sendBtn.disabled = false;
                    userInput.focus();
                });
            }

            readStream(); // 开始读取流
        }).catch(error => {
            hideTyping();
            addMessage(`请求失败: ${error.message}`, 'ai');
            sendBtn.disabled = false;
            userInput.focus();
        });
    } catch (error) {
        hideTyping();
        addMessage(`发生错误: ${error.message}`, 'ai');
        sendBtn.disabled = false;
        userInput.focus();
    }
}

        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 添加欢迎消息
        window.onload = () => {
            addMessage('你好！我是数据库智能查询助手，可以直接用自然语言查询数据库。例如："查询2025年的所有事件"', 'ai');
            userInput.focus();
        };
    </script>
</body>
</html>